var Turma = require('../classes/turma');
var Disciplina = require('../classes/disciplina');
var TurmaDAO = require('../DAO/turma.dao');
var DisciplinaDAO = require('../DAO/disciplina.dao');
var DisciplinaMapper = require('../mappers/disciplina.mapper');

function TurmaMapper() {
    var dao = new TurmaDAO();
    var discDAO = new DisciplinaDAO();
    var discMapper = new DisciplinaMapper();

    this.turmaToModel = function(t, callback) {
        var m = dao.getModel();
        discDAO.get(t.getDisciplina().getNome(), function(err, doc) {
            m._id = t.getId();
            m.disciplina.push(doc);
            m.vagas = t.getVagas();
            m.horario = t.getHorario();
            callback(m);
        });
    }

    this.modelToTurma = function(m, callback) {
        if(m instanceof Array) {
            var out = [];
            m.forEach(function(element) {
                discMapper.get(element.disciplina[0].nome, function(err, doc) {
                    var t = new Turma();
                    t.setId(element._id);
                    t.setVagas(element.vagas);
                    t.setHorario(element.horario);
                    t.setDisciplina(doc);
                    out.push(t);
                });
            });
            callback(out);
        }
        else {
            var t = new Turma();
            discMapper.get(m.disciplina[0].nome, function(err, doc) {
                t.setId(m._id);
                t.setVagas(m.vagas);
                t.setHorario(m.horario);
                t.setDisciplina(doc);
                callback(t);
            });
        }
    }

    this.add = function(t, callback) {
        this.turmaToModel(t, function(m) {
            dao.add(m, callback);
        });
    }

    this.getById = function(id, callback) {
        var that = this;
        dao.getById(id, function(err, doc) {
            that.modelToTurma(doc, function(t) {
                callback(err, t);
            });
        });
    }

    this.remove = function(t, callback) {
        this.turmaToModel(t, function(m) {
            dao.remove(m, callback);
        });
    }

    this.getAll = function(callback) {
        dao.getAll(callback);
    }
}

module.exports = TurmaMapper;
